//
//  WNReadPayManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/10/24.
//

import UIKit
import SwiftyStoreKit

//MARK: - 苹果支付充值
class WNReadPayManager: NSObject {
    
    static let shared = WNReadPayManager()
    
    /// 创建充值订单
    func creatReadRechargeOrder(_ taskId: Int, _ pid: String, _ pname: String, _ pids: String, _ price: Double) {
        WNBuriedManager.shared.initiatedCheckout(price)
        WNHUD.wn_showLiveAnimateLoading()
        provider_pay.rx.request(.creatReadRechargeOrder(taskId, pid, pname, pids))
            .asObservable().mapModel(BaseModel<PayOrderModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    WNHUD.wn_show(model.msg ?? "")
                    return
                }
                if let m = model.data, let orderId = m.orderId {
                    WNBuriedManager.shared.addedPaymentInfo(price)
                    self?.buyStoreProduct(orderId, pid, price)
                }else {
                    WNHUD.wn_hide()
                }
            }, onError: { (error) in
                WNHUD.wn_show("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 调起苹果支付订单
    func buyStoreProduct(_ orderId: String, _ productId: String, _ price: Double = 0.0) {
        isAppleLogin() ? setUserIdOrderId(orderId) : setUuidOrderId(orderId)
        var dic = [String: Any]()
        SwiftyStoreKit.purchaseProduct(productId) { [weak self] result in
            switch result {
            case let .success(purchase):
                var code: Int = 1
                let state = purchase.transaction.transactionState
                let tid = purchase.transaction.transactionIdentifier ?? ""
                switch state {
                case .purchased, .restored: code = 0
                default: break
                }
                if code == 0 {
                    WNBuriedManager.shared.purchase(price)
                }
                let receipt = SwiftyStoreKit.localReceiptData?.base64EncodedString()
                dic["code"] = code
                dic["msg"] = ""
                dic["orderId"] = orderId
                dic["tid"] = tid
                dic["receipt"] = receipt
                dic["price"] = price
                self?.verifyReadRecharge(dic, purchase)
            case let .error(error):
                var msg = "購買錯誤"
                switch error.code {
                case .paymentCancelled:
                    msg = "您已取消付款"
                case .paymentInvalid:
                    msg = "無效產品"
                default:
                    break
                }
                dic["code"] = 2
                dic["msg"] = msg
                dic["orderId"] = orderId
                self?.verifyReadRecharge(dic)
            }
        }
    }
    
    /// 苹果支付校验凭证
    func verifyReadRecharge(_ dic: [String: Any], _ purchase: PurchaseDetails? = nil) {
        let code = dic["code"] as? Int
        let msg = dic["msg"] as? String ?? ""
        let orderId = dic["orderId"] as? String ?? ""
        let tid = dic["tid"] as? String ?? ""
        let receipt = dic["receipt"] as? String ?? ""
        let price = dic["price"] as? Double ?? 0.0
        let complete = dic["complete"] as? Int
        guard !isBlank(orderId) else {
            return
        }
        provider_pay.rx.request(.verifyReadRecharge(orderId, tid, receipt))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { model in
                guard model.code == 0 else {
                    if complete != 1 {
                        WNHUD.wn_show(model.msg ?? "")
                    }
                    return
                }
                if let pur = purchase, pur.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(pur.transaction)
                }
                if code == 0 {
                    WNHUD.wn_show("購買成功！")
                    isAppleLogin() ? setUserIdOrderId("") : setUuidOrderId("")
                    if complete != 1 {
                        WNHUD.wn_show("購買成功！")
                    }
                    WNPayManager.shared.getBalance { _ in }
                    WNBuriedManager.shared.purchased(price)
                    NotificationCenter.default.post(name: WNNotiName.rechargeNoti, object: nil)
                }else {
                    WNHUD.wn_show(msg)
                }
            }, onError: { (error) in
                if complete != 1 {
                    WNHUD.wn_show("檢查網路連線")
                }
            }).disposed(by: rx.disposeBag)
    }
}
